echo off

REM ** PDO Database Build Script **
REM
REM Usage:
REM    %1 is database name, 
REM    %2 is directory for database files
REM    %3 is database server instance name (Optional)
REM    %4 is flag ("K") to kill (remove) database and re-create, else just drop tables
REM    %5 is flag ("P") to pause between steps 


REM -- Database name check ----------------------------
if  "%1" == "" goto :errorMissingArg1

REM Directory checks --
if (%2 == "") goto :errorMissingArg2

set oldpath=%cd%
if not exist "%2" goto :errorBadDirectory

REM -- Server instance name ------------------------
REM Provide default server instance name if not specified on command line
set DBNAME=%3
if not defined DBNAME set DBNAME="localhost"

REM -- Kill / Update flag check ---------------------
if "%4"=="K" goto labelRemove
if "%4"=="U" goto labelUpdate
if "%4"=="" goto labelUpdate
goto :erroroBadKillFlag


:labelUpdate
REM Drop any previously created tables.
echo.
echo Removing previously created tables from %1 database.
if "%5"=="P" pause
sqlcmd -S %DBNAME% -E -d %1 -i TableDrop.sql

goto :labelCreate


REM -- Kill (remove) existing database -----------------------------
:labelRemove

REM Terminating all connections to %1 database prior to attempting drop.
echo.
echo Removing any previous version of %1 database.
if "%5"=="P" pause
sqlcmd -S %DBNAME% -E -d master -i RemoveDB.sql -v dbname=%1

echo.
echo Creating new %1 database.
if "%5"=="P" pause
sqlcmd -S %DBNAME% -E -i DBCreate.sql -v dbname=%1 fileLoc=%2


REM -- Create tables -----------------------------
:labelCreate

echo.
echo Creating %1 tables.
if "%5"=="P" pause
sqlcmd -S %DBNAME% -E -d %1 -i TableCreate.sql

echo.
echo Creating PDO stored procedures for %1.
if "%5"=="P" pause
sqlcmd -S %DBNAME% -E -d %1 -i CRUD.sql

echo.
echo Adding %1 default data.
if "%5"=="P" pause
sqlcmd -S %DBNAME% -E -d %1 -i DefaultData.sql


echo End content creation for "%1" database.

goto :end



REM Error handling *********************************

:errorMissingArg1
echo Must specify a database name
goto :end

:errorMissingArg2
echo Must specify a directory 
goto :end

:errorBadDirectory
cd oldpath
echo Directory %2 does not exist
goto :end


:erroroBadKillFlag
echo Kill flag can have values of K or U (Optional)
goto :end

:end